import json
from json import dumps
from ssl import create_default_context
from pika import BlockingConnection
from pika.connection import Connection, ConnectionParameters, SSLOptions
from pika.credentials import PlainCredentials
from pika.spec import BasicProperties

class RabbitMQ(object):

    host: str = '127.0.0.1'
    address: str = '127.0.0.1'
    port: int = 5672
    ssl: bool = False
    virtual_host = '/'
    username: str = ''
    password: str = ''
    connection: Connection = None

    def __init__(self, host: str = None, address: str = None, port: int = 5672, ssl: bool = False, virtual_host: str = '/', username: str = '', password: str = ''):
        self.host = host
        if address:
            self.address = address
        else:
            self.address = host
        if port:
            self.port = port
        if ssl:
            self.ssl = ssl
        if virtual_host:
            self.virtual_host = virtual_host
        if username:
            self.username = username
        if password:
            self.password = password

    def get_connection(self) -> Connection:
        if self.connection:
            return self.connection

        params: ConnectionParameters = ConnectionParameters(
            host=self.host
        )

        if self.username or self.password:
            credentials: PlainCredentials = PlainCredentials(self.username, self.password)
            params.credentials = credentials

        if self.ssl:
            ssl_context = create_default_context()
            ssl_options = SSLOptions(ssl_context, self.address)
            params.ssl_options = ssl_options

        if self.port:
            params.port = self.port

        self.connection = BlockingConnection(params)
        return self.connection

    def get_channel(self):
        # 连接到RabbitMQ服务器
        connection = self.get_connection()
        return connection.channel()

    def send_message(self, exchange: str, routing_key: str, message: dict):
        channel = self.get_channel()

        # 发送消息到队列
        channel.basic_publish(
            exchange=exchange,
            routing_key=routing_key,
            body=dumps(message).encode('utf-8'),
            properties=BasicProperties(
                delivery_mode=2,
                content_type='application/json',
                content_encoding='utf-8'
            )
        )
        print(f"Sent message: {message} to queue: {exchange}, {routing_key}")

    def close(self):
        if self.connection:
            self.connection.close()
        self.connection = None
